package cn.devzyh.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class UploadUtil {

    /**
     * Web 上传文件
     *
     * @param file 文件对象
     * @param req  请求对象
     * @return 保存后的文件名称
     * @throws IOException
     */
    public static String upload(MultipartFile file, HttpServletRequest req) throws IOException {

        if (file.isEmpty()) {
            return null;
        }

        String uploadPath = req.getServletContext().getRealPath("/") + "../upload/";
        String newFileName = System.currentTimeMillis() + file.getOriginalFilename().
                substring(file.getOriginalFilename().lastIndexOf("."));

        File f = new File(uploadPath + newFileName);
        if (!f.exists()) {
            f.mkdirs();
        }

        file.transferTo(f);

        return newFileName;
    }
}
